package main

import (
	"context"
	"editor/constant"
	"editor/middleware"
	"editor/router"
	"errors"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

func main() {
	var err error
	r := gin.New()

	gin.SetMode(gin.ReleaseMode)

	// 注册中间件
	r.Use(middleware.MiddleWare())
	// Recovery
	r.Use(middleware.BaseParams())
	// Recovery
	r.Use(middleware.Recovery)
	// Session
	store := cookie.NewStore([]byte("secret11111"))
	r.Use(sessions.Sessions(constant.SessionCookieName, store))
	r.Use(middleware.Session())

	// 路由注册
	router.InitRouter(r)

	srv := &http.Server{
		Addr:         constant.Config.App.Port,
		Handler:      r,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
	}

	go func() {
		// 监听请求
		err = srv.ListenAndServe()
		if err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("http server failed, error: %v\n", err)
			return
		}
	}()

	// 优雅Shutdown（或重启）服务
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt) // syscall.SIGKILL
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("server shutdown: %v\n", err)
	}
	select {
	case <-ctx.Done():
	}
	log.Println("Server exiting")
}
